package com.sicheng.metadata.juc.jmm;

/**
 * @author zsc
 * @version 1.0
 * @date 2021/10/12 10:40
 */
public class HappensBefore {
    public static void main(String[] args) {
        new Thread(() -> {
            while (true) {

                System.out.println("read=" + read());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        new Thread(() -> {
            while (true) {
                write(i + 1);
                System.out.println("write=" + (i));
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();




        while (true) {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("主存="+i);
        }
    }

    private static int i;

    public static void write(int j) {
        i = j;
    }

    public static int read() {
        return i;
    }
}
